<?php
/**
 * @brief AOP处理类
 */
class Aop {
    /**
     * @var Aop AOP实例
     */
    protected static $instance;

    /**
     * @var array AOP列表
     */
    protected static $aopList;

    /**
     * 获取AOP实例
     *
     * @return Aop
     */
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取AOP列表
     *
     * @return boolean
     */
    public function getAopParser() {
        $yafRequest = Yaf_Registry::get('Yaf_Request');
        $controllerName = $yafRequest->controller;
        $className = $controllerName . '_Controller';
        $functionName = $yafRequest->action . 'Action';
        
        $ref = new ReflectionMethod($className, $functionName);
        $doc = $ref->getDocComment();
        $parser = new \Aop\Parser();
        self::$aopList = $parser->parse($doc);

        return true;
    }

    /**
     * 启动AOP
     *
     * @param string $type AOP类型: AopBefore / AopAfter / AopAround
     * 
     * @return boolean
     */
    public function runAop($type) {
        $list = self::$aopList[$type] ?? [];
        if ($list) {
            foreach ($list as $val) {
                $thisClass = $val['class'] ?? '';
                $thisFunction = $val['function'] ?? '';
                if ($thisClass && $thisFunction) {
                    $thisInstance = new $thisClass();
                    $thisInstance->$thisFunction();
                }
            }
        }

        return true;
    }
}
